package conn

import (
	"context"
	"fmt"
	"my-gameserver-go/logic/consts"
	"my-gameserver-go/logic/server/codec"
	"my-gameserver-go/logic/structs"
	"net"
	"sync"
)

type GameConnection struct {

	//当前连接的socket TCP套接字
	Conn *net.TCPConn
	//告知该链接已经退出/停止的channel
	Ctx    context.Context
	Cancel context.CancelFunc
	//有缓冲管道，用于读、写两个goroutine之间的消息通信
	MsgDispatchChan chan structs.ReqMessage //DispatchMessage routine channel
	MsgSendChan     chan structs.ResMessage
	Coder           *codec.TcpCoder
	sync.RWMutex
	//链接属性
	property map[string]interface{}
	////保护当前property的锁
	propertyLock sync.Mutex
	//当前连接的关闭状态
	Isclosed bool
}

//CreateConnection 创建连接的方法
func CreateConnection(conn *net.TCPConn) *GameConnection {
	//初始化Conn属性
	c := &GameConnection{
		Conn:            conn,
		Isclosed:        false,
		MsgDispatchChan: make(chan structs.ReqMessage, consts.MaxBufferSize),
		MsgSendChan:     make(chan structs.ResMessage, consts.MaxBufferSize),
		property:        make(map[string]any),
		Coder:           &codec.TcpCoder{HeadLen: 8},
	}
	//将新创建的Conn添加到链接管理中
	//c.TCPServer.GetConnMgr().Add(c)
	return c
}

func (conn *GameConnection) LogInfo() string {
	connState := conn.property[consts.ConnPlayerState]
	//chanelInfo := conn.Property[consts.ChannelInfo]
	return fmt.Sprintf("{connInfo:%s@channelInfo->connState:%s", conn.Conn.RemoteAddr().String(), connState)
}

func (conn *GameConnection) WriteMessage(message structs.ResMessage) {
	conn.MsgSendChan <- message
}

func (conn *GameConnection) GetCoder() *codec.TcpCoder {
	return conn.Coder
}

func (conn *GameConnection) Attr(key string) any {
	return conn.property[key]
}

func (conn *GameConnection) SetAttr(key string, v any) {
	conn.property[key] = v
}
func (conn *GameConnection) ClearAttr(key string) {
	conn.property[key] = nil
}
